<template>
  <div :class="`tw-libelupload x${_uid}`">
    <el-upload
      class="upload-demo"
      ref="libupload"
      :action="action"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="handleBeforeRemove"
      :multiple="multiple"
      :headers="headers"
      :on-change="handleChange"
      :limit="limit"
      :on-progress="handleProgress"
      :on-success="handleSuccess"
      :on-error="handleError"
      :before-upload="handleBeforeUpload"
      :list-type="listtype"
      :auto-upload="autoupload"
      :data="data"
      :drag="drag"
      :disabled="disabled || (limit > 0 && fileList.length >= limit)"
      :accept="accept"
      :with-credentials="withcredentials"
      :on-exceed="handleExceed"
      :show-file-list="showfilelist"
      :file-list="fileList">

      <template v-if="listtype==='avatar'">
        <div v-if="fileList.length > 0">
          <img :src="`${$twApp.fileBaseUrl}${fileList[0].localPath}`" class="avatar">
          <span class="avatar-uploader-icon">
            替换
          </span>
        </div>
        <template v-else>
          <img v-if="avatarBg.length > 0" :src="`${$twApp.fileBaseUrl}${avatarBg[0].localPath}`" class="avatar">
          <span class="avatar-uploader-icon">上传</span>
          <!-- <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
        </template>
      </template>

      <template v-else>
        <el-button :size="size" type="success" v-html="placeholder" :disabled="disabled || (limit > 0 && fileList.length >= limit)"></el-button>
        <div slot="tip" class="el-upload__tip" v-html="tips"></div>
      </template>

    </el-upload>
    <ul class="el-upload-list el-upload-list--text" v-if="useCustFilelist">
      <li tabindex="0" class="el-upload-list__item is-success" v-for="(file,idx) in fileList" :key="idx">
        <a class="el-upload-list__item-name" @click="handlePreview(file, idx)">
          <template v-if="useCustFileicon">
            <i v-if="file.iconCss && file.iconCss !==''" class="tw-ico" :class="file.iconCss"></i>
            <template v-else-if="icons.length>0">
              <img v-if="icons[1] && icons[1] !== '' && file.format && ['jpg', 'jpeg', 'gif', 'png', 'bmp'].includes(file.format)" class="xicon" :src="`${$twApp.fileBaseUrl}${icons[1].localPath}`" />
              <img v-else-if="icons[2] && icons[2] !== '' && file.format && ['doc', 'docx', 'wps'].includes(file.format)" class="xicon" :src="`${$twApp.fileBaseUrl}${icons[2].localPath}`" />
              <img v-else-if="icons[3] && icons[3] !== '' && file.format && ['xls', 'xlsx'].includes(file.format)" class="xicon" :src="`${$twApp.fileBaseUrl}${icons[3].localPath}`" />
              <img v-else-if="icons[4] && icons[4] !== '' && file.format && ['ppt', 'pptx'].includes(file.format)" class="xicon" :src="`${$twApp.fileBaseUrl}${icons[4].localPath}`" />
              <img v-else-if="icons[5] && icons[5] !== '' && file.format && ['pdf'].includes(file.format)" class="xicon" :src="`${$twApp.fileBaseUrl}${icons[5].localPath}`" />
              <img v-else-if="icons[6] && icons[6] !== '' && file.format && ['txt'].includes(file.format)" class="xicon" :src="`${$twApp.fileBaseUrl}${icons[6].localPath}`" />
              <img v-else-if="icons[7] && icons[7] !== '' && file.format && ['zip', 'rar', '7z'].includes(file.format)" class="xicon" :src="`${$twApp.fileBaseUrl}${icons[7].localPath}`" />
              <img v-else-if="icons[8] && icons[8] !== '' && file.format && ['mp4', 'avi', 'mpg', 'm3u8', 'mpeg', 'flv'].includes(file.format)" class="xicon" :src="`${$twApp.fileBaseUrl}${icons[8].localPath}`" />
              <img v-else class="xicon" :src="`${$twApp.fileBaseUrl}${icons[0].localPath}`" />
            </template>
          </template>
          <i class="el-icon-document" v-else></i>
          {{file.fileName}}
        </a>
        <label class="el-upload-list__item-status-label">
          <i class="el-icon-upload-success el-icon-circle-check"></i>
        </label>
        <i class="el-icon-close"  @click="handleRemove(file, idx)"></i>
        <el-progress
          v-if="file.status === 'uploading'"
          type="line"
          :stroke-width="2"
          :percentage="parseInt(file.percentage)">
        </el-progress>
      </li>
    </ul>
  </div>
</template>

<script>
import props from './props'
import { constants } from 'zlib';

export default {
  name: 'libinput',

  props,

  data() {
    return {
      fileList: [],
      disabled: false
    }
  },

  methods: {
    setStyle () {
      let style = ''

      if (this.useCustFilelist) {
        style += `
          .tw-libelupload.x${this._uid} .upload-demo {
            background-color: ${this.bgColor};
            padding: ${this.padding};
            text-align: ${this.textalign};
          }
          .tw-libelupload.x${this._uid} .el-upload-list {
            margin-top: -10px;
          }
          .tw-libelupload.x${this._uid} .el-upload-list__item {
            margin: ${this.listmargin};
            padding: ${this.listpadding};
            line-height: ${this.lineHeight};
          }
        `
      }

      if (this.listtype === 'avatar') {
        style += `
          .tw-libelupload.x${this._uid} .upload-demo {
            width: ${this.avatarWidth};
            height: ${this.avatarHeight};
            background-color: ${this.bgColor};
            padding: 0;//${this.padding};
            text-align: ${this.textalign};
            border-radius: ${this.avatarRadius};
            cursor: pointer;
            position: relative;
            overflow: hidden;
          }

          .tw-libelupload.x${this._uid} .upload-demo .avatar-uploader-icon {
            font-size: 14px;
            color: ${this.avatarColor};
            width: ${this.avatarWidth};
            height: ${this.avatarHeight};
            line-height: ${this.avatarHeight};
            background-color: ${this.avatarBgColor};
            text-align: center;
            position: absolute;
            left: 0;
            top: 0;
            display: none;
          }
          .tw-libelupload.x${this._uid} .upload-demo .avatar {
            width: ${this.avatarWidth};
            height: ${this.avatarHeight};
            display: block;
          }
          .tw-libelupload.x${this._uid} .upload-demo:hover .avatar-uploader-icon {
            display: block;
          }
        `
      }

      const styleEl = document.getElementById(this._uid) || document.createElement('style')
      styleEl.id = this._uid
      styleEl.innerText = style.replace(/\n/g, '')

      document.head.appendChild(styleEl)
    },

    handleRemove (file, idx) {
      if (this.disabled) {
        return
      }
      if (!this.validBeforeUpload(file, false)) {
        return
      }
      if (typeof this.onRemove === 'function') {
        this.onRemove(file, idx, this)
      } else {
        let that = this
        if (this.closeAlert) {
          that.fileList.splice(idx,1)
          window.$ui.msg.success("删除成功")
        } else {
          window.$ui.confirm('是否删除此附件？','提示',{
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            that.fileList.splice(idx,1)
            window.$ui.msg.success("删除成功")
          })
        }
      }
    },
    handlePreview (file, idx) {
      if (typeof this.onPreview === 'function') {
        this.onPreview(file, idx, this)
      }
    },
    handleExceed (files, fileList) {
      if (typeof this.onExceed === 'function') {
        this.onExceed(files, fileList, this)
      } else {
        if (this.listtype !== 'avatar') {
          window.$ui.msg.warning(`当前限制选择 ${this.limit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
        }
      }
    },
    handleBeforeRemove (file, fileList) {
      if (typeof this.beforeRemove === 'function') {
        this.beforeRemove(file, fileList, this)
      }
    },
    handleBeforeUpload (file) {
      return this.validBeforeUpload(file)
    },
    validBeforeUpload (file, showmsg = true) {
      if (this.beforeUpload !== '' &&  typeof this.beforeUpload === 'function') {
        return this.beforeUpload(file, this)
      } else {
        if (this.maxsize && this.maxsize.toUpperCase().indexOf('M') > -1) {
          if (file.size / 1024 / 1024 > parseFloat(this.maxsize)) {
            if (showmsg) {
              window.$ui.msg.warning(`上传文件大小不能超过 ${this.maxsize} `)
            }
            return false
          }
        } else if (this.maxsize && this.maxsize.toUpperCase().indexOf('K') > -1) {
          if (file.size / 1024 > parseFloat(this.maxsize)) {
            if (showmsg) {
              window.$ui.msg.warning(`上传文件大小不能超过 ${this.maxsize} `)
            }
            return false
          }
        }

        if (this.accept && file && file.name) {
          let filearr = file.name.split('.')
          let filetype = ''
          if (filearr.length > 0) {
            filetype = filearr[filearr.length - 1].toLowerCase()
          }
          if (filetype && !this.accept.split(', ').includes(filetype)) {
            if (showmsg) {
              window.$ui.msg.warning(`上传文件格式限制为：${this.accept} `)
            }
            return false
          }

          // docx .doc .wps .pdf .txt,.xlsx .xls .et .jpg .jpeg .bmp .png .gif .swf .rar .zip
        }

        return true
      }
    },
    handleError (err, file, fileList) {
      if (typeof this.onError === 'function') {
        this.onError(err, file, fileList, this)
      }
    },
    // handleHttpRequest () {

    // },
    handleSuccess(response, file, fileList) {
      if (typeof this.onSuccess === 'function') {
        this.onSuccess(response, file, fileList, this)
      } else {
        // let files = []
        // fileList.forEach((itm) => {
        //   if (itm.response && itm.response.fileInfos) {
        //     files.push({
        //       ...itm.response.fileInfos[0]
        //     })
        //   }
        // })
        // this.$emit('input', files)
        // this.$emit('change', files)
      }
    },
    handleProgress(event, file, fileList) {
      if (typeof this.onProgress === 'function') {
        this.onProgress(event, file, fileList, this)
      }
    },
    handleChange (files, fileList) {
      if (typeof this.onChange === 'function') {
        this.onChange(files, fileList, this)
      } else {
        if (!this.validBeforeUpload(files, false)) {
          return
        }
        let filesarr = []
        // console.log('fff', files)
        if (this.listtype === 'avatar') {
          if (files.response && files.response.fileInfos && files.response.fileInfos.length > 0) {
            filesarr.push({...files.response.fileInfos[0]})
            this.fileList = filesarr
            this.$emit('input', filesarr)
            this.$emit('change', filesarr)
          } else if (files.response && files.response.result) {
            filesarr.push({
              localPath: files.response.result,
              format: '',
              fileName: files.name
            })
            this.fileList = filesarr
            this.$emit('input', filesarr)
            this.$emit('change', filesarr)
          }
        } else {
          fileList.forEach((itm) => {
            if (itm.response && itm.response.fileInfos) {
              filesarr.push({
                ...itm.response.fileInfos[0]
              })
            } else {
              filesarr.push({...itm})
            }
          })
          this.fileList = filesarr
          this.$emit('input', filesarr)
          this.$emit('change', filesarr)
        }
      }
    },
    // submitUpload () {
    //   this.$refs.libupload.submit()
    //   this.$emit('input', this.fileList)
    //   this.$emit('change', this.fileList)
    // },
    disValue () {
      this.disabled = false
      if (this.validRules.length > 0) {
        this.validRules.forEach((itm) => {
          if (itm.disabled !== undefined && itm.disabled) {
            this.disabled = itm.disabled
          }
        })
      }
    }
  },

  computed: {
    headers () {
      let r = {}
      let branchCode = this.$twApp.user.branchCode || 'CXY0001'
      r = { branchCode: branchCode, 'Access-Token': this.$twApp.user.token, 'Current-Org-Id': this.$twApp.user.orgId }

      return r
    },
    data () {
      return null
    },
    style () {
      return {
        padding: this.padding,
        bgColor: this.bgColor,
        textalign: this.textalign,
        listpadding: this.listpadding,
        lineHeight: this.lineHeight,
        avatarWidth: this.avatarWidth,
        avatarHeight: this.avatarHeight,
        avatarRadius: this.avatarRadius,
        avatarColor: this.avatarColor,
        avatarBgColor: this.avatarBgColor,
      }
    }
  },

  mounted () {
    this.setStyle()
    this.fileList = this.value
    this.disValue()
  },

  watch: {
    value: {
      deep: true,
      handler () {
        this.fileList = this.value
      }
    },
    validRules: {
      deep: true,
      handler () {
        this.disValue()
      }
    },
    style: {
      deep: true,
      handler () {
        this.setStyle()
      }
    }
  }
}
</script>

<style lang="scss">
  @import './css/index.scss';
</style>
